package com.spark.gaea.utils.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.DateTimeSerializerBase;
import com.spark.gaea.utils.DateUtil;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateSerializer extends DateTimeSerializerBase<Date> {
	public DateSerializer() {
		this(false, null);
	}

	public DateSerializer(final boolean useTimestamp, final DateFormat customFormat) {
		super(Date.class, useTimestamp, customFormat);
	}

	@Override
	public DateTimeSerializerBase<Date> withFormat(final Boolean timestamp, final DateFormat customFormat) {
		if (timestamp != null && timestamp) {
			return new DateSerializer(true, null);
		}
		return new DateSerializer(false, customFormat);
	}

	@Override
	protected long _timestamp(final Date value) {
		return (value == null) ? 0L : value.getTime();
	}

	@Override
	public void serialize(final Date value, final JsonGenerator jgen, final SerializerProvider provider)
			throws IOException {
		if (this._useTimestamp) {
			jgen.writeNumber(this._timestamp(value));
		} else if (this._customFormat != null) {
			this._customFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
			synchronized (this._customFormat) {
				jgen.writeString(this._customFormat.format(value));
			}
		} else {
			jgen.writeString(DateUtil.format(value, "yyyy-MM-dd HH:mm"));
		}
	}
}
